package com.srwl.mytx.fragment;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.LiveRoomSearchActivity;
import com.srwl.mytx.adapter.LiveRoomListAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.service.LiveService;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.widget.NodataFooter;
import com.srwl.mytx.activity.CreateLiveRoomActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.dkzwm.widget.srl.MaterialSmoothRefreshLayout;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import me.dkzwm.widget.srl.extra.footer.MaterialFooter;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

//import io.agora.AgoraAPIOnlySignal;

/**
 * A simple {@link Fragment} subclass.
 */
public class LiveListFragment extends Fragment {
    private static final String TAG = LiveListFragment.class.getSimpleName();
    private static final int REQUEST_CODE_CREATE_LIVE_ROOM = 0;
    private static final int REQUEST_CODE_EDIT_TOPIC = 1;
    private int currentPage = 1;
    private MaterialSmoothRefreshLayout refreshLayout;
    private RecyclerView rv_liveRoomList;
    private LiveRoomListAdapter liveRoomListAdapter;
    private List<LiveRoom> roomList = new ArrayList<>();

    private ImageView iv_release;
    private RelativeLayout rl_search;

    protected InputMethodManager inputMethodManager;
    private boolean hasNextPage = true;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;
    private ProgressBar progressBar;
    private View searchResultEmpty;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        roomList = new ArrayList<>();
        liveRoomListAdapter = new LiveRoomListAdapter(getContext(), this, roomList);
        loadData(false);
        //监听刷新聊天室列表
        registerBroadcastReceiver();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_live_list, container, false);
        searchResultEmpty = view.findViewById(R.id.search_result_empty);
        rv_liveRoomList = view.findViewById(R.id.rl_live_room_list);
        rv_liveRoomList.setLayoutManager(new GridLayoutManager(getContext(), 2));
        rv_liveRoomList.setAdapter(liveRoomListAdapter);
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        iv_release = view.findViewById(R.id.iv_release);
        rl_search = view.findViewById(R.id.rl_search);
        progressBar = view.findViewById(R.id.progress_bar);

//        view.findViewById(R.id.img_backout).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (listener != null) {
//                    listener.onChangeFragment();
//                }else return;
//            }
//        });

        rl_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), LiveRoomSearchActivity.class));
            }
        });


        iv_release.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
//                String phoneNumber = UserProfileManager.getInstance().getUserPhoneNumber();
//                if (TextUtils.isEmpty(phoneNumber)) {
//                    ConfirmDialog confirmDialog = new ConfirmDialog(getContext(), "提示", "绑定手机号才可以创建聊天室，去绑定？", true);
//                    confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
//                        @Override
//                        public void confirm() {
//                            startActivity(new Intent(getActivity(), UpdateUserInfoActivity.class));
//                        }
//                    });
//                    confirmDialog.show();
//                } else {
//                    startActivityForResult(new Intent(getActivity(), CreateLiveRoomActivity.class), REQUEST_CODE_CREATE_LIVE_ROOM);
//                    //    hideSoftKeyboard();
//                }
                startActivityForResult(new Intent(getActivity(), CreateLiveRoomActivity.class), REQUEST_CODE_CREATE_LIVE_ROOM);
            }
        });

        initRefreshView(view);
        return view;
    }


    private void search(String query) {
        Map<String, Object> info = new HashMap<>();
        info.put("queryContent", query);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .searchLiveRoom(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (progressBar.isShown()) {
                            progressBar.setVisibility(View.GONE);
                        }

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "ES搜索失败：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "ES搜索失败：" + result.getMsg());
                            return;
                        }

                        JSONObject jsonObject = (JSONObject) result.getData();
                        Log.d(TAG, "ES搜索完成" + jsonObject);
                        List<Topic> resultsList = JSONObject.parseArray(jsonObject.getString("hits"), Topic.class);

                        if (resultsList == null || resultsList.size() == 0) {
                            if (!searchResultEmpty.isShown()) {
                                searchResultEmpty.setVisibility(View.VISIBLE);
                            }
                            return;
                        }
                        roomList.clear();
                        List<LiveRoom> liveRooms = new ArrayList<>();
                        for (Topic topic : resultsList) {
                            LiveRoom liveRoom = new LiveRoom();
                            liveRoom.setId(topic.getId());
                            liveRoom.setManagerId(topic.getManagerId());
                            liveRoom.setChatId(topic.getId());
                            liveRoom.setTitle(topic.getTitle());
                            liveRoom.setStatus(topic.getStatus());
                            liveRoom.setVideo(topic.getVideo());
                            if (topic.getPictures() != null && topic.getPictures().size() != 0) {//图片和视频，至少有一样存在
                                liveRoom.setCover(topic.getPictures().get(0));
                            } else {
                                liveRoom.setCover(topic.getVideoCover());
                            }
                            liveRooms.add(liveRoom);
//                            agoraAPIOnlySignal.channelQueryUserNum(liveRoom.getId());
                        }
                        roomList.addAll(liveRooms);
                        liveRoomListAdapter.notifyDataSetChanged();
                        //  showToast("查询成功");
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "ES搜索失败：" + t.getMessage());
                        if (progressBar.isShown()) {
                            progressBar.setVisibility(View.GONE);
                        }

                    }
                });

    }

    void initRefreshView(View view) {
        refreshLayout = view.findViewById(R.id.refresh_layout);
        refreshLayout.setEnableOverScroll(true);//关掉会出现，item 重建后，第一次点击事件无须，会被refreshLayout 拦截掉
        // refreshLayout.setDisableRefresh(true);//注释掉，允许下拉刷新
        refreshLayout.setDisableLoadMore(false);
        //   refreshLayout.setEnableAutoLoadMore(true);
//        refreshLayout.setOnLoadMoreScrollCallback(new SmoothRefreshLayout.OnLoadMoreScrollCallback() {
//            @Override
//            public void onScroll(View content, float delta) {
//
//                rv_liveRoomList.scrollBy(0, (int) delta);
//            }
//        });
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                if (refreshLayout.getFooterView() instanceof NodataFooter) {
                    refreshLayout.setFooterView(new MaterialFooter(getActivity()));
                }
                //不能在此情况数据，应该在数据请求完成之后，根据是否是刷新操作，再清空旧数据
                // roomList.clear();
                currentPage = 1;
                loadData(true);
            }

            @Override
            public void onLoadingMore() {
                if (hasNextPage) {
                    loadData(false);
                } else {
                    refreshLayout.refreshComplete();
                    Log.d(TAG, "onRefreshBegin: 没有更多数据了");
                }
            }

        });
    }


    private void loadData(boolean isRefresh) {
        if (!Helper.getInstance().isNetworkConnected()) {
            if (refreshLayout != null) refreshLayout.refreshComplete();
            Toast.makeText(getContext(), getContext().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Object> body = new HashMap<>();
        body.put("page", currentPage);
        body.put("size", 20);

        if (searchResultEmpty != null && searchResultEmpty.isShown()) {
            searchResultEmpty.setVisibility(View.GONE);
        }
        RetrofitManager.getInstance().createRequest(LiveService.class)
                .getLiveRoom(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        refreshLayout.refreshComplete();

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "获取live列表出错：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "获取live列表出错：" + result.getMsg());
                            return;
                        }
                        JSONObject jsonObject = (JSONObject) result.getData();
                        hasNextPage = jsonObject.getBoolean("hasNextPage");
                        if (!hasNextPage) {
                            refreshLayout.postDelayed(() -> {
                                if (getActivity() != null) {
                                    refreshLayout.setFooterView(new NodataFooter(getActivity()));
                                }
                            }, 1000);
                        }

                        List<LiveRoom> liveRooms = jsonObject.getJSONArray("list").toJavaList(LiveRoom.class);
                        if (isRefresh) {
                            roomList.clear();
                            roomList.addAll(liveRooms);
                            liveRoomListAdapter.notifyDataSetChanged();
                        } else {
                            roomList.addAll(liveRooms);
                            liveRoomListAdapter.notifyItemRangeInserted(roomList.size() - liveRooms.size(), liveRooms.size());
                        }
                        currentPage++;
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        if (progressBar != null) {
                            progressBar.setVisibility(View.GONE);
                        }
                        refreshLayout.refreshComplete();
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    protected void hideSoftKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        broadcastManager.unregisterReceiver(broadcastReceiver);
    }

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(getContext());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_TOPIC_EDIT_CHANGED);
        intentFilter.addAction(Constant.ACTION_TOPIC_MANAGER_TRANSFER);
        intentFilter.addAction(Constant.ACTION_TOPIC_MANAGER_REMOVE);
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                switch (action) {
                    case Constant.ACTION_TOPIC_EDIT_CHANGED: {
                        Topic updateTopic = intent.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
                        if (updateTopic == null) {
                            return;
                        }
                        for (int index = 0; index < roomList.size(); index++) {
                            if (TextUtils.equals(roomList.get(index).getId(), updateTopic.getId())) {
                                LiveRoom liveRoom = roomList.get(index);
                                boolean isUpdated = false;
                                List<String> pictures = updateTopic.getPictures();
                                if (pictures.size() != 0 && !TextUtils.equals(pictures.get(0), liveRoom.getCover())) {
                                    liveRoom.setCover(pictures.get(0));
                                    isUpdated = true;
                                }
                                if (!TextUtils.equals(updateTopic.getVideo(), liveRoom.getVideo())) {
                                    liveRoom.setVideo(updateTopic.getVideo());
                                    isUpdated = true;
                                }
                                if (isUpdated) {
                                    liveRoomListAdapter.notifyItemChanged(index);
                                }
                                break;
                            }
                        }

                        break;
                    }
                    case Constant.ACTION_TOPIC_MANAGER_REMOVE:
                    case Constant.ACTION_TOPIC_MANAGER_TRANSFER:
                        Topic updateTopic = intent.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
                        if (updateTopic == null) {
                            return;
                        }
                        for (int index = 0; index < roomList.size(); index++) {
                            if (TextUtils.equals(roomList.get(index).getId(), updateTopic.getId())) {
                                LiveRoom liveRoom = roomList.get(index);
                                liveRoom.setManagerId(updateTopic.getManagerId());
                                roomList.set(index, liveRoom);
                                // liveRoomListAdapter.notifyItemChanged(index);
                                break;
                            }
                        }
                        break;
                }


            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: 执行了，");

        if (resultCode != Activity.RESULT_OK || data == null) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_EDIT_TOPIC:
                LiveRoom updateLiveRoom = data.getParcelableExtra(Constant.EXTRA_INFO_LIVE_ROOM);
                for (int index = 0; index < roomList.size(); index++) {
                    if (TextUtils.equals(roomList.get(index).getId(), updateLiveRoom.getId())) {
                        roomList.set(index, updateLiveRoom);
                        liveRoomListAdapter.notifyItemChanged(index);
                        break;
                    }
                }
                break;
            case REQUEST_CODE_CREATE_LIVE_ROOM:
                LiveRoom liveRoom = data.getParcelableExtra(Constant.EXTRA_INFO_LIVE_ROOM);
                roomList.add(0, liveRoom);
                liveRoomListAdapter.notifyDataSetChanged();//因为插到入第一个，所有item都需要刷新
                rv_liveRoomList.smoothScrollToPosition(0);
//                agoraAPIOnlySignal.channelQueryUserNum(liveRoom.getId());
                break;
        }

    }
}
